package up

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

const (
	key             = "LTAI5t7f**e1TQh***VK1"
	AccessKeySecret = "jthYxrU***408ule***CGY2nSPO"
	Endpoint        = "oss-cn-hangzhou.aliyuncs.com"
	BucketName      = "li***on"
	渠道              = "shihuo"
)

var (
	long = 0
	ti1  = int64(0)
)

func Uploads(str []interface{}) []interface{} {
	for k, v := range str {
		str[k] = Upload(v.(string))
	}
	return str
}

func Upload(url string) string {

	// 创建OSSClient实例。
	client, err := oss.New(Endpoint, key, AccessKeySecret)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	t1 := time.Now().Unix()
	if ti1 != t1 { //如果时间戳不一样,那么归零
		long = 0
	}
	ti1 = t1
	long++
	obj := fmt.Sprintf(渠道+"/%d%d.jpg", t1, long)
	// 获取存储空间。
	bucket, err := client.Bucket(BucketName)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	// 上传Byte数组。
	err = bucket.PutObject(obj, bytes.NewReader(ReadImgData(url)))
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	return "https://" + BucketName + "." + Endpoint + "/" + obj
}

//获取C的图片数据
func ReadImgData(url string) []byte {
	resp, err := http.Get(url)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	pix, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}
	return pix
}
